/*
** my_delete_from_list.c for  in /home/gomes_m//zappy-2016-gomes_m/server
** 
** Made by mickael gomes
** Login   <gomes_m@epitech.net>
** 
** Started on  Fri Jul 12 15:33:24 2013 mickael gomes
** Last update Tue Jul 23 14:19:59 2013 mickael gomes
*/

#include		<stdlib.h>
#include		<stdio.h>
#include		"struct.h"
#include		"prototypes.h"

t_list			*option_1(t_list *list)
{
  t_list		*tmp;

  tmp = list->next;
  xclose(list->fd);
  free(list);
  list = tmp;
  return (list);
}

t_list			**option_2(t_list **list, int fd)
{
  t_list		*save;
  t_list		*tmp;

  tmp = *list;
  while (tmp->next->fd != fd)
    tmp = tmp->next;
  save = tmp->next->next;
  xclose(tmp->next->fd);
  free(tmp->next);
  tmp->next = save;
  return (list);
}

int			get_position_in_list(t_list *list, int fd, int list_len)
{
  int			pos = 0;

  while (list->next != NULL && list->fd != fd)
    {
      list = list->next;
      pos++;
    }
  if (pos == list_len)
    return (0);
  return (pos);
}

int			get_list_len(t_list *list)
{
  int			len = 0;

  while (list != NULL)
    {
      list = list->next;
      len++;
    }
  return (len);
}

void			my_delete_from_list(t_list **list, int fd)
{
  int			list_len;
  int			pos;

  if ((list_len = get_list_len(*list)) == 0)
    return ;
  pos = get_position_in_list(*list, fd, list_len);
  if (list_len >= 1 && pos == 0)
    *list = option_1(*list);
  else
    list = option_2(list, fd);
}
